/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package foalvleditor.core;

/**
 *
 * @author Mikael
 */


import foalvleditor.core.impl.LevelModel;
import foalvleditor.gameobjects.GameEvent;
import foalvleditor.gameobjects.AbstractGameObject;
import java.io.StringWriter;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XMLParser {

    public static String parseLevel() throws ParserConfigurationException, CloneNotSupportedException {

        ArrayList<AbstractGameObject> level=LevelModel.getInstance().getLevel();
        AbstractGameObject levelBg=LevelModel.getInstance().getBackground();
        ArrayList<GameEvent> events=LevelModel.getInstance().getEvents();
        String titleString=LevelModel.getInstance().getName();
        String xml="";
        if (!level.isEmpty()){
        Document xmldoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element resources=xmldoc.createElement("resources");
        xmldoc.appendChild(resources);

        //creates objects
        for (int i=0; i<level.size(); i++){
            Element objectbit=xmldoc.createElement("objectBit");
            objectbit.setAttribute("bitmap", level.get(i).getBitmap().getBitmapCode());
            objectbit.setAttribute("objectType", level.get(i).getName());
            objectbit.setAttribute("position", level.get(i).getPosition().x+","+level.get(i).getPosition().y);
            objectbit.setAttribute("layer", String.valueOf(level.get(i).getLayer()));
            objectbit.setAttribute("id", String.valueOf(i));
            resources.appendChild(objectbit);
            }

        //creates background
        if (levelBg!=null)
        {
            Element background=xmldoc.createElement("objectBit");
        background.setAttribute("bitmap", levelBg.getBitmap().getBitmapCode());
        background.setAttribute("objectType", levelBg.getName());
        background.setAttribute("position", "0,0");
        background.setAttribute("layer", String.valueOf(levelBg.getLayer()));
        background.setAttribute("id", String.valueOf(level.size()));
        resources.appendChild(background);
        }

        //creates events
        if (!events.isEmpty()){

            // iterates through all the events (ArrayLists)
            for (int i=0; i<events.size(); i++)
            {
            GameEvent thisEvent=events.get(i);
            Element eventList=xmldoc.createElement("event");
            eventList.setAttribute("id", String.valueOf(100+i));
            eventList.setAttribute("eventType", events.get(i).getType().displayableName);
            if (thisEvent.getType().equals(GameEvent.EventType.SWITCH))
                eventList.setAttribute("create", "true");
            String objectNumbers="";
            String firstObj="";

            // iterates through all the objects in the current event list
            for (int j=0; j<thisEvent.getObjectList().size(); j++)
            {

                //if the object is in the level, it is added to the list.
                for (int k=0; k<level.size(); k++)
                {
                    if (level.get(k)==thisEvent.getObjectList().get(j))
                    {
                        if (objectNumbers.length()==0)
                        {
                            objectNumbers+=(String.valueOf(k));
                        }
                        else
                        {
                            objectNumbers+=(","+k);
                        }
                    }
                }
                System.out.println(objectNumbers);
            }

            // find first object too
            for (int l=0; l<level.size(); l++)
            {
              if (level.get(l)==events.get(i).getFirstObject())
              {
                    firstObj=String.valueOf(l);
              }
            }

            if (thisEvent.getType().equals(GameEvent.EventType.SWITCH))
                {
                eventList.setAttribute("bind", firstObj);
            }
            else{
                objectNumbers=firstObj+","+objectNumbers;
            }
            System.out.println(objectNumbers);
            eventList.setAttribute("objects", objectNumbers);
            resources.appendChild(eventList);
            }
        }

        //creates a <plaintag> with level title
        Element title=xmldoc.createElement("plaintag");
        title.setTextContent(titleString);
        resources.appendChild(title);

        try{
            Transformer t = TransformerFactory.newInstance().newTransformer();
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            t.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter sw=new StringWriter();
            StreamResult result=new StreamResult(sw);
            DOMSource source=new DOMSource(xmldoc);
            t.transform(source, result);
            xml=sw.toString();
            }
        catch (TransformerException e) {
            JOptionPane.showMessageDialog(null, "Error while parsing XML");
        }

        }
        return xml;

    }
}

